package com.mycomp.cm.dao.impl;

import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.mycomp.cm.dao.ContactDAO;
import com.mycomp.cm.model.Contact;

@Repository
public class ContactDAOImpl implements ContactDAO {

	private SessionFactory sessionFactory;

	@Autowired
	public ContactDAOImpl(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Transactional
	public void save(Contact contact) {
		sessionFactory.getCurrentSession().save(contact);
	}

	
	@Transactional
	public void delete(int contID) {
		Contact contact = (Contact) sessionFactory.getCurrentSession().get(
				Contact.class, contID);
		sessionFactory.getCurrentSession().delete(contact);
	}


	@Transactional
	public void update(Contact contact) {
		sessionFactory.getCurrentSession().merge(contact);
	}


	@Transactional(readOnly = true)
	public Contact findByID(int contID) {
		Contact contact = (Contact) sessionFactory.getCurrentSession().get(
				Contact.class, contID);
		return contact;
	}

	
	@Transactional(readOnly = true)
	public Set<Contact> findAll() {
		Criteria criteria = sessionFactory.getCurrentSession().createCriteria(
				Contact.class);
		@SuppressWarnings("unchecked")
		List<Contact> list = criteria.list();
		return new TreeSet<Contact>(list);
	}

}
